import React from "react";
import { JustObject, PaginationI } from "@/models/common";
import { Column } from "@/models/components/Table";
import cls from "@/styles/components/Table.module.scss";
import { Pagination } from "@/components/Pagination/Pagination";

type Props = {
  data: JustObject[];
  columns: Column[];
  isLoading: boolean;
  pagination?: PaginationI;
  onRowClick?: (item: JustObject) => void;
};

const Table = ({ data, columns, isLoading, pagination, onRowClick }: Props) => {
  return (
    <div className={cls.wrapper}>
      <div className={cls.root}>
        <table>
          <thead>
            <tr>
              {columns.map((column) => (
                <th key={column.key} style={{ width: `${column.width}%` }}>
                  <div className={cls.thWrapper}>
                    <h4>{column.name}</h4>
                  </div>
                </th>
              ))}
            </tr>
          </thead>

          <tbody>
            {!isLoading && !!data && (
              <>
                {data.length !== 0 &&
                  data.map((item) => (
                    <tr key={item.id} onClick={() => onRowClick(item)}>
                      {columns.map((column) => (
                        <td key={column.key}>
                          {column.cell ? column.cell(item) : item[column.key]}
                        </td>
                      ))}
                    </tr>
                  ))}
                {data.length === 0 && (
                  <tr>
                    <td colSpan={columns.length}>Ничего не найдено</td>
                  </tr>
                )}
              </>
            )}

            {isLoading && (
              <tr className={cls.empty}>
                <td colSpan={columns.length}>
                  <span className="loader2" />
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
      {pagination && <Pagination pagination={pagination} />}
    </div>
  );
};

export default Table;
